package com.sptpc.learnspring.controller;

import com.sptpc.learnspring.controller.request.NewDrinkRequest;
import com.sptpc.learnspring.model.Drink;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/drink")
public class DrinkController {

    @ModelAttribute
    public List<Drink> drinkList() {
        List<Drink> list = new ArrayList<>();
        list.add(Drink.builder().id(1).name("茉莉绿茶")
                .price(Money.of(CurrencyUnit.of("CNY"), 12.00)).build());
        list.add(Drink.builder().id(2).name("四季春茶")
                .price(Money.of(CurrencyUnit.of("CNY"), 8.00)).build());
        list.add(Drink.builder().id(3).name("焦糖冰拿铁")
                .price(Money.of(CurrencyUnit.of("CNY"), 18.00)).build());
        return list;
    }

    @GetMapping("/")
    public ModelAndView getAllDrinks() {
        return new ModelAndView("all-drinks");
    }

    @GetMapping("/{id}")
    public ModelAndView getDrinkById(@PathVariable Integer id) {
        ModelAndView mv = new ModelAndView("drink-info");
        // 模拟从数据库通过id查询饮品数据
        Drink drink = Drink.builder().id(3).name("焦糖冰拿铁")
                .price(Money.of(CurrencyUnit.of("CNY"), 18.00)).build();
        mv.addObject("drink", drink);
        return mv;
    }

    @GetMapping("/to-add")
    public ModelAndView toAddForm() {
        return new ModelAndView("create-drink-form");
    }

    // 模板使用Form表单进行提交
    @PostMapping(value = "/add",
            consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
    public String addNewDrink(@Valid NewDrinkRequest newDrink) {
        log.info("创建新饮品{}", newDrink);
        Drink drink = new Drink();
        BeanUtils.copyProperties(newDrink, drink);
        drink.setId(2);
        log.info("创建成功");
        return "redirect:/drink/";
    }

}
